#include "machineutil.h"
#include <QCryptographicHash>
#include "mylogger.h"
#include <QProcess>

using namespace ns_yht;

QString MachineUtil::g_globalMachineCode = ""; //"1ac3a5bba5858aa26da05f9105f061b6";  //测试用设备码，正常为空

MachineUtil::MachineUtil()
{
}

MachineUtil::~MachineUtil()
{
}

QString MachineUtil::machineCode()
{
    if (g_globalMachineCode.isEmpty())
    {
        MachineUtil mutil;
        g_globalMachineCode = mutil.getMachineId();
    }
    return g_globalMachineCode;
}

void MachineUtil::setMachineCode(const QString &machineCode)
{
    g_globalMachineCode = machineCode;
}

QString MachineUtil::getMachineId()
{

#ifdef Q_OS_WIN
    QString uuid = QSysInfo::machineUniqueId();
    if (uuid.isEmpty() || uuid.length() < 2)
    {
        uuid = getWMIC("baseboard get serialnumber");
        if (uuid.isEmpty())
        {
            // 原来海图桌里获取硬盘序列号会变，可能是插入U盘并且U盘的index为0（一般不会），此时获取的序列号为0
            uuid = getWMIC("diskdrive where index=0 get serialnumber");
            if (uuid.isEmpty() || uuid.length() < 2)
            {
                uuid = getWMIC("diskdrive where index=1 get serialnumber");
                if (uuid.isEmpty() || uuid.length() < 2)
                {
                    uuid = getWMIC("csproduct get uuid");
                    ;
                    if (uuid.isEmpty())
                    {
                        if (GLOG)
                            GLOG->info("getMachineId failed!");
                        return "";
                    }
                    else
                        uuid = "csproduct uuid: " + uuid;
                }
            }
            else
                uuid = "diskdrive serialnumber: " + uuid;
        }
        else
            uuid = "baseboard serialnumber: " + uuid;
    }
    else
        uuid = "machineUniqueId: " + uuid;
    uuid = QCryptographicHash::hash(uuid.toUtf8(), QCryptographicHash::Md5).toHex();
    return uuid;

#else
    QString uuid = QSysInfo::machineUniqueId(); // 黑匣子遇到重启就改变的情况
    if (uuid.isEmpty() || uuid.length() < 2)
    {
        uuid = getWMIC("ip link show | grep 'link/ether' | awk '{print $2}'");
        if (uuid.isEmpty() || uuid.length() < 2)
        {
            uuid = getWMIC("cat /etc/machine-id");
            if (uuid.isEmpty() || uuid.length() < 2)
            {
                if (GLOG)
                    GLOG->info("getMachineId failed!");
                return "";
            }
            else
                uuid = "machine id: " + uuid;
        }
        else
            uuid = "netcard address: " + uuid;
    }
    else
        uuid = "machineUniqueId: " + uuid;

    uuid = QCryptographicHash::hash(uuid.toUtf8(), QCryptographicHash::Md5).toHex();
    return uuid;
#endif
}

QString MachineUtil::getWMIC(const QString &cmd)
{
    // 获取cpu名称：wmic cpu get Name
    // 获取cpu核心数：wmic cpu get NumberOfCores
    // 获取cpu线程数：wmic cpu get NumberOfLogicalProcessors
    // 查询cpu序列号：wmic cpu get processorid
    // 查询主板序列号：wmic baseboard get serialnumber
    // 查询BIOS序列号：wmic bios get serialnumber
    // 查看硬盘：wmic diskdrive get serialnumber
    QProcess p;
#ifdef Q_OS_WIN
    // p.start(cmd);
    p.start("wmic", {cmd.split(' ', Qt::SkipEmptyParts)}, QIODevice::ReadOnly);
#else
    p.setProgram("bash");
    p.setArguments({"-c", cmd});
    p.start();
#endif
    p.waitForFinished();
    QString result = QString::fromLocal8Bit(p.readAllStandardOutput());
    QStringList list = cmd.split(" ");
    result = result.remove(list.last(), Qt::CaseInsensitive);
    result = result.replace("\r", "");
    result = result.replace("\n", "");
    result = result.replace(QRegExp("\\/"), "");
    result = result.simplified();
    qInfo() << "getWMIC " << cmd << "  " << result;
    return result.toUtf8();
}
